<template>
  <!-- :rules="rules" -->
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item :label="t('accessControl.userManagement.roles')" prop="roles">
        <el-select multiple v-model="selectRolesData" :placeholder="t('accessControl.userManagement.roles')" clearable>
          <el-option v-for="item in rolesData" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
        </el-select>
      </el-form-item>

      <el-form-item label="技术组" prop="belongsGroupStr">
        <el-tree-select
          style="width: 180px"
          v-model="orgSelect"
          :data="treeFilterData"
          :render-after-expand="false"
          show-checkbox
          check-strictly
          check-on-click-node
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">{{ t("common.cancel") }}</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">{{ t("common.confirm") }}</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { User } from "@/api/interface";
import { getRoleList, getUserDepartment } from "@/api/modules/user";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

//获取所属部门
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  if (data) {
    treeFilterData.value = data;

    traverseTree(treeFilterData.value[0], node => {
      if (node.attr.orgNo.toString() == "1") {
        node["disabled"] = true;
      }
      node.label = node.attr.orgName;
      node.value = node.attr.orgNo;
    });

    console.log(treeFilterData.value);
  }
};
onMounted(() => {
  getTreeFilter();
  getRole();
});
// const stateVal = ref("");
const state = [
  {
    value: true,
    label: t("accessControl.userManagement.enabled")
  },
  {
    value: false,
    label: t("accessControl.userManagement.disabled")
  }
];
const holiday = [
  {
    value: false,
    label: t("accessControl.userManagement.onDuty")
  },
  {
    value: true,
    label: t("accessControl.userManagement.onHoliday")
  }
];
interface Role {
  roleId: string;
  roleName: string;
}

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  val?: any[] | undefined;
  isadd: boolean;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  isadd: false,
  title: "",
  val: [],
  row: {}
});

const selectRolesData = ref<Role[]>([]);
const rolesData = ref<Role[]>([]);
//获取用户角色
const getRole = async () => {
  const data = await getRoleList();
  rolesData.value = data.data as Role[];
};
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  selectRolesData.value = [];
  belongsGroupSelect.value = [];

  drawerProps.value = params;
  drawerVisible.value = true;
  //  traverseTree(treeFilterData.value[0], node => {
  //    // console.log(node.attr.orgName == drawerProps.value.row.orgName);
  //    if (node.attr.orgName == drawerProps.value.row.orgName) {
  //      orgSelect.value = node.attr.orgNo;
  //    }
  // if(drawerProps.value.row.belongsGroupStr!=undefined && drawerProps.value.row.belongsGroupStr!=""){
  // 	let groupArr = drawerProps.value.row.belongsGroupStr.split(",");
  // 	 for (let j = 0; j < groupArr.length; j++) {
  // 			   if (node.attr.orgName == groupArr[j]) {
  // 				   belongsGroupSelect.value.push(node.attr.orgNo)
  // 			   }
  // 	 }
  // }

  //  });
  //  if(drawerProps.value.row!.roles!=undefined &&drawerProps.value.row!.roles !=""){
  //   for (let i = 0; i < rolesData.value.length; i++) {
  //   	  let arr = drawerProps.value.row!.roles.split(",");
  //   	   for (let j = 0; j < arr.length; j++) {
  //   		   if (rolesData.value[i]["roleName"] == arr[j]) {
  //   			   selectRolesData.value.push(rolesData.value[i]["roleId"])
  //   		   }
  //   	   }
  //   }
  //  }
};
const belongsGroupSelect = ref([]);
const orgSelect = ref("");

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  try {
    if (selectRolesData.value.length <= 0) {
      ElMessage.error(t("accessControl.userManagement.pleaseSelectRole"));
      return;
    }

    let roleIdsStr = "";
    for (let i = 0; i < selectRolesData.value.length; i++) {
      if (roleIdsStr == "") {
        roleIdsStr = "?userDto.roleIds=" + selectRolesData.value[i];
      } else {
        roleIdsStr = roleIdsStr + "&userDto.roleIds=" + selectRolesData.value[i];
      }
    }
    const userInfo = reactive({
      "userDto.orgNo": orgSelect.value,
      "userDto.roleIdsStr": roleIdsStr
    });

    drawerProps.value.api!(userInfo).then(res => {
      ElMessage.success({ message: "角色赋予组成功" });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    });
  } catch (error) {
    console.log(error);
  }
};
interface Tree {
  label: string;
  children?: Tree[];
  attr: any;
}
interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
  label: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
defineExpose({
  acceptParams
});
</script>
